package cn.com.ry.framework.application.meteor.meteor.javacode.web;

import ch.ethz.ssh2.Connection;
import cn.com.ry.framework.application.meteor.framework.exception.ValidationException;
import cn.com.ry.framework.application.meteor.framework.json.XjjJson;
import cn.com.ry.framework.application.meteor.framework.security.annotations.SecCreate;
import cn.com.ry.framework.application.meteor.framework.security.annotations.SecEdit;
import cn.com.ry.framework.application.meteor.framework.security.annotations.SecList;
import cn.com.ry.framework.application.meteor.framework.security.annotations.SecPrivilege;
import cn.com.ry.framework.application.meteor.framework.ssh.SshTool;
import cn.com.ry.framework.application.meteor.framework.web.SpringControllerSupport;
import cn.com.ry.framework.application.meteor.meteor.javacode.entity.JavacodeEntity;
import cn.com.ry.framework.application.meteor.meteor.machineinfo.entity.MachineinfoEntity;
import cn.com.ry.framework.application.meteor.meteor.machineinfo.service.MachineinfoService;
import cn.com.ry.framework.application.meteor.meteor.websocket.service.WebsocketService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.OutputStream;

@Controller
@RequestMapping("/meteor/javacode")
public class JavacodeController extends SpringControllerSupport {
    @Autowired
    private MachineinfoService machineinfoService;
    @Autowired
    private WebsocketService websocketService;

    @SecPrivilege(title = "java代码编辑器")
    @SecList
    @RequestMapping(value = "/index")
    public String index(Model model) {
        String page = this.getViewPath("index");
        return page;
    }

    @SecCreate
    @SecEdit
    @RequestMapping("/save")
    @ResponseBody
    public XjjJson save(@ModelAttribute JavacodeEntity javacodeEntity, HttpSession session) {
        validateSave(javacodeEntity);
        boolean flag = false;
        MachineinfoEntity machineinfoEntity = (MachineinfoEntity) session.getAttribute("meteor_param");
        if (null == machineinfoEntity) {
            return XjjJson.error("session失效，请重新登录！");
        }
        Connection connection = null;
        try {
            connection = websocketService.getConnection(machineinfoEntity.getId());
            byte[] data = javacodeEntity.getCode().getBytes();
            try {
                flag = SshTool.uploadAndUnTar(connection, data, javacodeEntity.getCodeName(), "meteor");
            } catch (ValidationException e) {
                throw new ValidationException("文件上传失败", e);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != connection) {
                connection.close();
                connection = null;
            }
        }
        if (flag) {
            return XjjJson.success("上传成功");
        } else {
            return XjjJson.error("上传失败");
        }
    }

    /**
     * 数据校验
     **/
    private void validateSave(JavacodeEntity javacodeEntity) {
        //必填项校验
        if (null == javacodeEntity.getCode()) {
            throw new ValidationException("代码不能为空");
        }
        if (null == javacodeEntity.getCodeName()) {
            throw new ValidationException("代码文件名不能为空");
        }

    }

    /**
     * 下载文件
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("/download/{filename}")
    public String downLoad(@PathVariable(value = "filename") String filename, HttpSession session, HttpServletResponse response) {
        MachineinfoEntity machineinfoEntity = (MachineinfoEntity) session.getAttribute("meteor_param");
        String filePath = "/tmp/meteor/" + filename + ".java";
        Long machineId = machineinfoEntity.getId();
        Connection connection = null;
        try {
            connection = websocketService.getConnection(machineId);
            response.setContentType("application/octet-stream");
            response.setHeader("Content-disposition", "attachment; filename=" + filename + ".java");
            OutputStream outputStream = response.getOutputStream();
            SshTool.download(connection, filePath, outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != connection) {
                connection.close();
            }
        }
        return null;
    }


}

